package eeui.android.WxWechatPlugin.module;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.widget.Toast;

import com.taobao.weex.annotation.JSMethod;
import com.taobao.weex.bridge.JSCallback;
import com.taobao.weex.common.WXModule;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.Map;

import eeui.android.WxWechatPlugin.util.RootCmd;

public class AppWxWechatPluginModule extends WXModule {

    /**
     * 简单演示
     * @param msg
     */
    @JSMethod
    public void simple(String msg) {
        Toast.makeText(mWXSDKInstance.getContext(), msg, Toast.LENGTH_SHORT).show();
    }

    /**
     * 回调演示
     * @param msg
     * @param callback
     */
    @JSMethod
    public void call(final String msg, final JSCallback callback) {
        AlertDialog.Builder localBuilder = new AlertDialog.Builder(mWXSDKInstance.getContext());
        localBuilder.setTitle("demo");
        localBuilder.setMessage(msg);
        localBuilder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (callback != null) {
                    callback.invoke("返回：" + msg); //多次回调请使用invokeAndKeepAlive
                }
            }
        });
        AlertDialog dialog = localBuilder.setCancelable(false).create();
        dialog.show();
    }

    /**
     * 同步返回演示
     * @param msg
     * @return
     */
    @JSMethod(uiThread = false)
    public String retMsg(String msg) {
        return "返回：" + msg;
    }

    private Activity getCurrentActivity () {
        try {
            Class activityThreadClass = Class.forName("android.app.ActivityThread");
            Object activityThread = activityThreadClass.getMethod("currentActivityThread").invoke(
                    null);
            Field activitiesField = activityThreadClass.getDeclaredField("mActivities");
            activitiesField.setAccessible(true);
            Map activities = (Map) activitiesField.get(activityThread);
            for (Object activityRecord : activities.values()) {
                Class activityRecordClass = activityRecord.getClass();
                Field pausedField = activityRecordClass.getDeclaredField("paused");
                pausedField.setAccessible(true);
                if (!pausedField.getBoolean(activityRecord)) {
                    Field activityField = activityRecordClass.getDeclaredField("activity");
                    activityField.setAccessible(true);
                    Activity activity = (Activity) activityField.get(activityRecord);
                    return activity;
                }
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return null;
    }


    @JSMethod(uiThread = true)
    public void goWechatScan() {
//        this.toWeChatScanDirect(this.getCurrentActivity());

        this.toWeChatWalletScanner(this.getCurrentActivity());
//        this.toTestMe(this.getCurrentActivity());

//        this.toWeChatPayCode(this.getCurrentActivity());
//        this.toAliPayScan(this.getCurrentActivity());
//        this.toAliPayCode(this.getCurrentActivity());
//        this.toWeChatDirect(this.getCurrentActivity());

    }

    @JSMethod(uiThread = true)
    public void goWechatPayCode() {

//        this.toWeChatPayCode(this.getCurrentActivity());
        this.toTestMe(this.getCurrentActivity());
    }

    @JSMethod(uiThread = true)
    public void goWechatWallet() {
        this.toWeChatWallet(this.getCurrentActivity());
    }

    @JSMethod(uiThread = true)
    public void goWechatWalletBalance() {
        this.toWeChatWalletBalance(this.getCurrentActivity());
    }

    @JSMethod(uiThread = true)
    public void goWechatBank() {
        this.toWeChatBank(this.getCurrentActivity());
    }

    @JSMethod(uiThread = true)
    public void goAliPayScan() {
//        this.toWeChatScanDirect(this.getCurrentActivity());
        this.toAliPayScan(this.getCurrentActivity());
    }

    @JSMethod(uiThread = true)
    public void goAliPayCode() {
//        this.toWeChatScanDirect(this.getCurrentActivity());
        this.toAliPayCode(this.getCurrentActivity());
    }

    @JSMethod(uiThread = true)
    public void goWechatCollect() {
//        this.toWeChatScanDirect(this.getCurrentActivity());
        this.toWeChatCollect(this.getCurrentActivity());
    }

//    @JSMethod(uiThread = true)
//    public void toWeChatDirect(Context context) {
//        try {
//            //利用Intent打开微信
//            Uri uri = Uri.parse("weixin://");
////            Uri uri = Uri.parse("weixin://dl/scan");
//            Intent intent3 = new Intent(Intent.ACTION_VIEW, uri);
//            context.startActivity(intent3);
////            startActivity(intent3);
//        } catch (Exception e) {
//            //若无法正常跳转，在此进行错误处理
//            Toast.makeText(this.getCurrentActivity(), "无法跳转到微信，请检查您是否安装了微信！", Toast.LENGTH_SHORT).show();
//        }
//    }

    public void toAliPayDirect(Context context) {
        try {
            //利用Intent打开支付宝

            Uri uri = Uri.parse("alipayqr://platformapi/startapp?saId=10000007");
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            context.startActivity(intent);
        } catch (Exception e) {
            //若无法正常跳转，在此进行错误处理
            Toast.makeText(this.getCurrentActivity(), "无法跳转到支付宝，请检查您是否安装了支付宝！", Toast.LENGTH_SHORT).show();
        }

    }

    public void toAliPayCode(Context context) {
        try {
            //利用Intent打开支付宝

            Uri uri = Uri.parse("alipayqr://platformapi/startapp?saId=20000056");
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            context.startActivity(intent);
        } catch (Exception e) {
            //若无法正常跳转，在此进行错误处理
            Toast.makeText(context, "无法跳转到支付宝，请检查您是否安装了支付宝！", Toast.LENGTH_SHORT).show();
        }
    }

    @SuppressLint("WrongConstant")
    public void toWeChatScanDirect(Context context) {
        try {
            Intent intent = new Intent();
            intent.setComponent(new ComponentName("com.tencent.mm", "com.tencent.mm.ui.LauncherUI"));
            intent.putExtra("LauncherUI.From.Scaner.Shortcut", true);
//            intent.setComponent(new ComponentName("com.tencent.mm", "com.tencent.mm.plugin.setting.ui.qrcode.GetQRCodeInfoUI"));
//            intent.setComponent(new ComponentName("com.tencent.mm", "com.tencent.mm.plugin.offline.ui.WalletOfflineCoinPurseUI"));
//            intent.putExtra("LauncherUI.From.Scaner.Shortcut", true);
//            intent.putExtra("LauncherUI.From.Coder.Shortcut", true);
            intent.setFlags(335544320);
            intent.setAction("android.intent.action.VIEW");
            context.startActivity(intent);
        } catch (Exception e) {
        }
    }

    @SuppressLint("WrongConstant")
    public void toTestMe(Context context) {
        try {
            Intent intent = new Intent();
            intent.setComponent(new ComponentName("com.nativeplus.tvpayshop", "app.eeui.playground.WelcomeActivity"));
//
            intent.putExtra("pageTo", "guanggao");
            intent.setFlags(335544320);
            intent.setAction("android.intent.action.VIEW");
            context.startActivity(intent);
        } catch (Exception e) {
        }
    }

    @SuppressLint("WrongConstant")
    public void toWeChatPayCode(Context context) {
//        ComponentName componetName = new ComponentName(
//                "com.tencent.mm",  //这个是另外一个应用程序的包名
//                "com.tencent.mm.plugin.scanner.ui.BaseScanUI");   //这个参数是要启动的Activity的全路径名
//
//        try {
//            Intent intent = new Intent();
//            intent.setComponent(componetName);
//            context.startActivity(intent);
//        } catch (Exception e) {
//            Toast.makeText(context, "可以在这里提示用户没有找到应用程序，或者是做其他的操作！", 0).show();
//        }

//        try {
////            Intent intent = new Intent(Intent.ACTION_VIEW,Uri.parse("market://com.trywang.jartest/abc?abc=1234"));
////            intent.addCategory(Intent.CATEGORY_DEFAULT);
////            PackageManager packageManager = getPackageManager();
////            List activities = packageManager.queryIntentActivities(intent,
////                    PackageManager.MATCH_DEFAULT_ONLY);
////            boolean isIntentSafe = activities.size() > 0;
////            if (isIntentSafe) {
////                context.startActivity(intent);
////            }
//            Uri data = Uri.parse("weixin://qr");
//            Intent intent = new Intent(Intent.ACTION_VIEW,data);
//            //保证新启动的APP有单独的堆栈，如果希望新启动的APP和原有APP使用同一个堆栈则去掉该项
//            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//            try {
//                context.startActivity(intent);
//            } catch (Exception e) {
//                e.printStackTrace();
//                Toast.makeText(this.getCurrentActivity(), "没有匹配的APP，请下载安装",Toast.LENGTH_SHORT).show();
//            }
//
//        } catch (Exception e) {
//        }
        String cmd="am start -n com.tencent.mm/.plugin.offline.ui.WalletOfflineCoinPurseUI";
//        String cmd="am start -n com.tencent.mm/.plugin.mall.ui.MallWalletUI";
//        String cmd="am start -n com.tencent.mm/.plugin.collect.ui.CollectMainUI";
//        String cmd="am start -n com.tencent.mm/.plugin.wallet_index.ui.WalletOpenFingerprintPayRedirectUI";
//        String cmd="am start -n com.tencent.mm/.plugin.wallet.balance.ui.WalletBalanceManagerUI";
//        String cmd="am start -n com.tencent.mm/.plugin.wallet.balance.ui.WalletBalanceFetchUI";
//        String cmd="am start -n com.tencent.mm/.plugin.webview.ui.tools.QRCodeIntroductionWebViewUI";
        RootCmd.execRootCmd(cmd);
//        String cmd="am start -n com.tencent.mm/.plugin.offline.ui.WalletOfflineCoinPurseUI";
//        String cmd="am start -n com.tencent.mm/com.tencent.mm.plugin.scanner.ui.BaseScanUI";
//        try {
//            Process p = Runtime.getRuntime().exec(cmd);
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
    }

    @SuppressLint("WrongConstant")
    public void toWeChatWallet(Context context) {

//        String cmd="am start -n com.tencent.mm/.plugin.offline.ui.WalletOfflineCoinPurseUI";
        String cmd="am start -n com.tencent.mm/.plugin.mall.ui.MallWalletUI";
//        String cmd="am start -n com.tencent.mm/.plugin.collect.ui.CollectMainUI";
//        String cmd="am start -n com.tencent.mm/.plugin.wallet_index.ui.WalletOpenFingerprintPayRedirectUI";
//        String cmd="am start -n com.tencent.mm/.plugin.wallet.balance.ui.WalletBalanceManagerUI";
//        String cmd="am start -n com.tencent.mm/.plugin.wallet.balance.ui.WalletBalanceFetchUI";
//        String cmd="am start -n com.tencent.mm/.plugin.webview.ui.tools.QRCodeIntroductionWebViewUI";
        RootCmd.execRootCmd(cmd);
    }

    @SuppressLint("WrongConstant")
    public void toWeChatWalletBalance(Context context) {

//        String cmd="am start -n com.tencent.mm/.plugin.offline.ui.WalletOfflineCoinPurseUI";
//        String cmd="am start -n com.tencent.mm/.plugin.mall.ui.MallWalletUI";
//        String cmd="am start -n com.tencent.mm/.plugin.collect.ui.CollectMainUI";
//        String cmd="am start -n com.tencent.mm/.plugin.wallet_index.ui.WalletOpenFingerprintPayRedirectUI";
        String cmd="am start -n com.tencent.mm/.plugin.wallet.balance.ui.WalletBalanceManagerUI";
//        String cmd="am start -n com.tencent.mm/.plugin.wallet.balance.ui.WalletBalanceFetchUI";
//        String cmd="am start -n com.tencent.mm/.plugin.webview.ui.tools.QRCodeIntroductionWebViewUI";
        RootCmd.execRootCmd(cmd);
    }

    @SuppressLint("WrongConstant")
    public void toWeChatWalletScanner(Context context) {

//        String cmd="am start -n com.tencent.mm/.plugin.offline.ui.WalletOfflineCoinPurseUI";
//        String cmd="am start -n com.tencent.mm/.plugin.mall.ui.MallWalletUI";
//        String cmd="am start -n com.tencent.mm/.plugin.collect.ui.CollectMainUI";
//        String cmd="am start -n com.tencent.mm/.plugin.wallet_index.ui.WalletOpenFingerprintPayRedirectUI";
        String cmd="am start -n com.tencent.mm/.plugin.scanner.ui.BaseScanUI";
//        String cmd="am start -n com.tencent.mm/.plugin.wallet.balance.ui.WalletBalanceFetchUI";
//        String cmd="am start -n com.tencent.mm/.plugin.webview.ui.tools.QRCodeIntroductionWebViewUI";
        RootCmd.execRootCmd(cmd);
    }

    @SuppressLint("WrongConstant")
    public void toWeChatBank(Context context) {

//        String cmd="am start -n com.tencent.mm/.plugin.offline.ui.WalletOfflineCoinPurseUI";
//        String cmd="am start -n com.tencent.mm/.plugin.mall.ui.MallWalletUI";
//        String cmd="am start -n com.tencent.mm/.plugin.collect.ui.CollectMainUI";
//        String cmd="am start -n com.tencent.mm/.plugin.wallet_index.ui.WalletOpenFingerprintPayRedirectUI";
        String cmd="am start -n com.tencent.mm/.plugin.wallet.bind.ui.WalletBankcardManageUI";
//        String cmd="am start -n com.tencent.mm/.plugin.wallet.balance.ui.WalletBalanceFetchUI";
//        String cmd="am start -n com.tencent.mm/.plugin.webview.ui.tools.QRCodeIntroductionWebViewUI";
        RootCmd.execRootCmd(cmd);
    }

    @SuppressLint("WrongConstant")
    public void toWeChatCollect(Context context) {

//        String cmd="am start -n com.tencent.mm/.plugin.offline.ui.WalletOfflineCoinPurseUI";
//        String cmd="am start -n com.tencent.mm/.plugin.mall.ui.MallWalletUI";
//        String cmd="am start -n com.tencent.mm/.plugin.collect.ui.CollectMainUI";
//        String cmd="am start -n com.tencent.mm/.plugin.wallet_index.ui.WalletOpenFingerprintPayRedirectUI";

        String cmd="am start -n com.tencent.mm/.ui.contact.ChatroomContactUI";
//        String cmd="am start -n com.tencent.mm/.plugin.wallet.balance.ui.WalletBalanceFetchUI";
//        String cmd="am start -n com.tencent.mm/.plugin.webview.ui.tools.QRCodeIntroductionWebViewUI";
        RootCmd.execRootCmd(cmd);

//        Intent intent = new Intent();
//        ComponentName cmp = new ComponentName("com.tencent.mm", "com.tencent.mm.ui.LauncherUI");
//        intent.setAction(Intent.ACTION_MAIN);
//        intent.addCategory(Intent.CATEGORY_LAUNCHER);
//        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//        intent.setComponent(cmp);
//        context.startActivity(intent);
    }

    public static void toAliPayScan(Context context)
    {
        try
        {
            Uri uri = Uri.parse("alipayqr://platformapi/startapp?saId=10000007");
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            context.startActivity(intent);
        } catch (Exception e)
        {
            Toast.makeText(context, "打开失败，请检查是否安装了支付宝", Toast.LENGTH_SHORT).show();
        }
    }

    public static boolean isWeixinAvilible(Context context) {
        final PackageManager packageManager = context.getPackageManager();// 获取packagemanager
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);// 获取所有已安装程序的包信息
        if (pinfo != null) {
            for (int i = 0; i < pinfo.size(); i++) {
                String pn = pinfo.get(i).packageName;
                if (pn.equals("com.tencent.mm")) {
                    return true;
                }
            }
        }
        return false;
    }
}
